package com.ceit.controller.interceptor;

import com.ceit.dao.UserRoleMapper;
import com.ceit.service.loginS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

/**
 * Created by 隼 on 2016/12/5.
 * 登陆认证拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private loginS loginS;
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String url = httpServletRequest.getRequestURI();
        System.out.println(url);
        if(url.contains("/login")){
            System.out.println("登录");
            return true;

        }else {
            String role;
            HttpSession session=httpServletRequest.getSession();
            if(session.getAttribute("role")==null||session.getAttribute("role")==""){
                role=  String.valueOf( 5);                   //5是游客的意思
            }else {
                role = String.valueOf(session.getAttribute("role"));
            }
            List<String> stringList=loginS.getAuthorityByRole(Integer.parseInt(role));
            Iterator<String> iterator=stringList.iterator();
            Boolean T=false;
            if(url.equals("/")){
                T=true;
                httpServletRequest.getRequestDispatcher("/WEB-INF/view/index.jsp").forward(httpServletRequest, httpServletResponse);

            }

                while (iterator.hasNext()) {
                    String successurl=iterator.next();
                    System.out.println(successurl+"允许的网址");
                    if (url.contains(successurl)) {
                        T=true;
                        return true;
                    }
                }
                if(T==false){
                        httpServletRequest.getRequestDispatcher("/WEB-INF/view/refuse.jsp").forward(httpServletRequest, httpServletResponse);
                    }


            return false;
        }

    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
